package org.example.MqttDemo;

import org.eclipse.paho.client.mqttv3.*;
import org.example.obj.MqttConfiguration;

public class MqttAsync {
    private MqttConfiguration MO;
    private MqttAsyncClient connect;

    public MqttAsync(MqttConfiguration MO) {
        this.MO = MO;
    }

    public MqttAsync() {
    }


    public void status() {
        String url = MO.getBrokerUrl()+":"+MO.getPort();

        try {
            connect = new MqttAsyncClient(url,MO.getClientID());
            connect.connect(MO.getMO(), new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken iMqttToken) {
                    System.out.println("链接成功");
                    try {
                        connect.subscribe(MO.getTopic(),MO.getQos());
                    } catch (MqttException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
                    System.out.println(throwable);
                }
            });

        } catch (MqttException e) {
            System.out.println("错误"+e);

        }

        connect.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {

            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                System.out.println(s);
                System.out.println(mqttMessage.getQos());
                System.out.println(new String(mqttMessage.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });

    }
    public Boolean sendMessage(String message,boolean retained){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if(MO.getTopic().length() == 1 || MO.getTopic().length() > MO.getMAXTOPIC()   )
        {
            System.out.println("====topic长度不符合规则====");
            return false;
        }
        if(MO.getTopic().contains(" ") || MO.getTopic().isEmpty()){
            System.out.println("====topic不能有空格或者为空====");
            return false;
        }

        try {
            connect.publish(MO.getTopic(),message.getBytes(), MO.getQos(), retained);
            return true;
        } catch (MqttException e) {
            System.out.println("========="+e+"=========");
            return false;
        }

    }

}
